﻿#include"XQTimerGroup.h"
#include"XQFuncEvent.h"
#include"XQFuncEventFilter.hpp"
#include<QCoreApplication>
#include<QThread>
#include<QTimer>
#include<QDebug>
XQTimerGroup::XQTimerGroup(QObject* parent)
	:QThread(parent)
{
	init();
}

XQTimerGroup::~XQTimerGroup()
{
	m_condition.wakeAll();
	requestInterruption();
	quit();
	wait();
	//if (m_tirmer != nullptr)
	//	m_tirmer->deleteLater();
}

int XQTimerGroup::pollTime() const
{
	return m_pollTime;
}

XQTimerTask* XQTimerGroup::task(int id) 
{
	QReadLocker lock(&m_lock);
	if(m_taskGroup.find(id)==m_taskGroup.end())
		return nullptr;
	return &m_taskGroup[id];
}

void XQTimerGroup::setPollTime(int msec)
{
	m_pollTime=msec;
}

int XQTimerGroup::addTask(const XQTimerTask& task, int id)
{
	if (id < -1)
	{
		qWarning() << __FUNCTION__ << "-添加定时器任务失败了,id不合法:(合法id:0开始)" << id;
		return id;
	}
	QWriteLocker lock(&m_lock);
	if (id == -1)
	{
		id = getId(id);
	}
	else if (m_taskGroup.find(id) != m_taskGroup.end())
	{
		qWarning() << __FUNCTION__ << "-添加定时器任务失败了,id重复:" << id;
		return -1;
	}
	m_taskGroup[id]=task;
	/*lock.unlock();*/
	//qInfo() << "加入任务 " << m_taskGroup.size()<< &m_taskGroup;
	if (m_taskGroup.size() == 1)
		m_condition.wakeAll();
	return id;
}

int XQTimerGroup::addTask(QDateTime runTime, qint64 sec, std::function<void()> task, qint64 count, bool mainThread, int id)
{
	if (sec < 0)
	{
		qWarning() << __FUNCTION__ << "时间间隔参数不对-sec:" << sec;
		return -1;
	}
	return addTask(XQTimerTask(runTime, count, sec, task, mainThread),id);
}

int XQTimerGroup::addTask(qint64 sec, std::function<void()> task, bool mainThread, int id)
{
	return addTask(QDateTime::currentDateTime(),sec, task,-1, mainThread,id);
}

int XQTimerGroup::addTask(QDateTime runTime, std::function<QDateTime(XQTimerTask*)> upTimeFunc, std::function<void()> task, qint64 count, bool mainThread, int id)
{
	return addTask(XQTimerTask(runTime, count, upTimeFunc, task, mainThread), id);
}

bool XQTimerGroup::removeTask(int id)
{
	QWriteLocker lock(&m_lock);
	return m_taskGroup.remove(id);;
}

void XQTimerGroup::clearTask()
{
	QWriteLocker lock(&m_lock);
	m_taskGroup.clear();
}

void XQTimerGroup::init()
{
	installEventFilter(new XQFuncEventFilter(this));
	start();
}

int XQTimerGroup::getId(int id)
{
	/*QReadLocker lock(&m_lock);*/
	auto list = m_taskGroup.keys();
	for (int i = 0; i < INT_FAST32_MAX; i++)
	{
		if (list.indexOf(i) == -1)
			return i;
	}
	return -1;
}

void XQTimerGroup::timerSlot()
{
	QWriteLocker lock(&m_lock);
	//qInfo() << "轮询中"<< m_taskGroup.size()<<&m_taskGroup;
	for (auto it= m_taskGroup.begin();it!= m_taskGroup.end();)
	{
		auto& task = it.value();
		if (!task.isEnabled())
			continue;//任务是禁用状态跳过当前的
		//判断是否可以运行
		if (task.isRunTask())
		{
			emit pollState(TimerPollState::run,it.key());
			if (task.isMainThreadRun())
				new XQFuncEvent(this, [&] {task.runTask();});
			else
				task.runTask();//运行任务	
			emit runTimeUpData(it.key(),task.runTime());
			if (task.isCountFinish() && task.isAutoDelete())
			{
				emit pollState(TimerPollState::remove, it.key());
				it = m_taskGroup.erase(it);
				//qInfo() << "删除任务";
				continue;
			}
		}
		it++;
	}
}

void XQTimerGroup::run()
{
	m_time= QDateTime::currentDateTime();
	//qInfo() << "线程循环id:" << QThread::currentThreadId();
	while (!isInterruptionRequested())
	{
		emit pollState(TimerPollState::poll);
		auto current = QDateTime::currentDateTime();
		auto msec = m_time.msecsTo(current);
		if (msec < m_pollTime)
		{
			QThread::msleep(m_pollTime - msec);
			continue;
		}
		m_time = current;
		timerSlot();
		QReadLocker lock(&m_lock);
		if (m_taskGroup.size() == 0)//没任务的时候休眠线程
		{
			/*qDebug() << "线程休眠";*/
			emit pollState(TimerPollState::sleep);
			m_condition.wait(&m_lock);
			emit pollState(TimerPollState::wake);
		/*	qDebug() << "线程唤醒";*/
		}
	}
}
